var sys = require("util");
var ws = require("./node_modules/websocket-server");

function log(data) {
	sys.log("\033[0;32m"+data+"\033[0m");
}

var server = ws.createServer();
server.listen(8080);

server.addListener("connection", function(connection) {
	log("connected");
	connection.addListener("message", function(msg){
    	server.send(msg);
  });
});

server.addListener("request", function(req, res) {
	res.writeHead(200, {"Content-Type" : "text/plain"});
	res.write("OK !!!");
	res.end();
});

server.addListener("client", function(connection) {
	log(connection._id + ": new connection");
	
	connection.addListener("readyStateChange", function(readyState) {
		log("stateChange:" + readyState);
	});

	connection.addListener("open", function() {
		log(connection._id + ": onOpen");
		server.clients.forEach(function(client){
			client.write("New connection: " + connection._id);
		})
	});

	connection.addListener("close", function() {
		log(connection._id + ": onClose");
		server.clients.forEach(function(client){
			client.write("Connection closed: " + connection._id);
		})
	});

	connection.addListener("message", function(message) {
		log(connection._id + ": "+JSON.stringify(message));
	    server.clients.forEach(function(client){
	      client.write(connection._id + ": "+message);
	    });
	});
});
